package com.hzlj.position.locate.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fz.common.base.core.RequestHolder;
import com.fz.common.base.exception.PubException;
import com.hzlj.position.locate.cache.DifferentiationConfigCache;
import com.hzlj.position.locate.common.dto.differentiationConfig.DifferentiationConfigQueryResultDTO;
import com.hzlj.position.locate.common.enums.DifferentiationDataType;
import com.hzlj.position.locate.differentiation.DifferentiationService;
import com.hzlj.position.locate.service.DifferentiationConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 独立业务-配置(DifferentiationConfig)表服务接口
 *
 * @author makejava
 * @date 2024-05-28 11:02:03
 */
@Slf4j
@Service
public class DifferentiationConfigServiceImpl implements DifferentiationConfigService {
    @Resource
    private DifferentiationConfigCache differentiationConfigCache;
    @Resource
    private ApplicationContext applicationContext;

    @Override
    public DifferentiationService getService(DifferentiationService callService,
                                             DifferentiationDataType type,
                                             String jgCode) {
        if (ObjectUtil.isEmpty(jgCode)) {
            log.warn("jgCode为空，不能获取handler:callService={},type={},jgCode={}", callService, type, jgCode);
            return null;
        }
        DifferentiationConfigQueryResultDTO config = differentiationConfigCache.getConfig(type.getDataType(), jgCode);
        if (config == null) {
            return null;
        }
        DifferentiationService differentiationService = applicationContext.getBean(StrUtil.lowerFirst(config.getHandler()), DifferentiationService.class);
        if (differentiationService == callService) {
            log.warn("存在死循环调用，请检查是否没有继承:callService={},differentiationService={},type={},jgCode={}"
                    , callService, differentiationService, type, jgCode);
            throw new PubException("存在死循环调用");
        }        //添加threadLocal
        RequestHolder.add(config);
        return differentiationService;
    }
}
